package com;

import com.handlers.BeanConstants;
import com.handlers.Constants;

import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;

public class MiniBasicRowProcessor implements MiniRowProcessor{

    private MiniBeanProcessor convert = null;

    public MiniBasicRowProcessor(MiniBeanProcessor convert) {
        super();
        this.convert = convert;
    }

    public MiniBasicRowProcessor() {
        this(BeanConstants.DEFAULT_BEAN_PROCESSOR);
    }

    @Override
    public Object[] toArray(ResultSet rs) throws SQLException {
        ResultSetMetaData metaData = rs.getMetaData();
        int counts = metaData.getColumnCount();
        Object[] result=new Object[counts];
        for (int i = 0; i < counts; i++) {
            result[i]=rs.getObject(i+1);
        }
        return result;
    }

    @Override
    public Map<String, Object> toMap(ResultSet rs) throws SQLException {
        Map<String,Object> result=new HashMap<>();
        ResultSetMetaData metaData = rs.getMetaData();
        int counts = metaData.getColumnCount();
        for (int i = 0; i < counts; i++) {
            Object filedValue=rs.getObject(i+1);
            String filedName = metaData.getColumnLabel(i + 1);
            if(filedName == null || filedName.length()==0){
                filedName = metaData.getColumnName(i + 1);
            }
            result.put(filedName,filedValue);
        }
        return result;
    }

    @Override
    public <T> T toBean(ResultSet rs, Class<? extends T> type) throws SQLException {
        return this.convert.toBean(rs,type);
    }
}
